package cn.qinhao.pethome.org.controller;

import cn.qinhao.pethome.annotation.PreAuthorize;
import cn.qinhao.pethome.basic.until.AjaxResult;
import cn.qinhao.pethome.basic.until.PageList;
import cn.qinhao.pethome.org.domain.Department;
import cn.qinhao.pethome.org.query.DepartmentQuery;
import cn.qinhao.pethome.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
/**
 * 部门控制器
 *
 *    @RestController : 标记该控制器类 ，支持Restful 风格api设计 ，该注解是一个组合注解 @Controller + @ResponseBody
 *                      从而该接口中所有方法都将以json格式返回数据。
 *
 *    @PathVariable("xx") : 从url路径中获取数据绑定到方法参数上，比如xx/{id} 要获得路径中的id 则 @PathVariable("id")
 *    @RequestBody: 从前端获得json数据映射到参数实体上。
 *
 *    @GetMapping: 强调获得数据请求
 *    @DeleteMapping： 删除数据请求
 *    @PutMapping：修改数据请求/增加
 *    @PostMapping：万能（提交数据请求）
 *    Swagger
 *    @Api(value = "部门的API",description="部门相关的CRUD功能") ：打在Controller对Controller做描述
 *    @ApiOperation(value = "通过ID查询" ) ：打在方法上，对方法做描述
 *    @ApiParam(name="ID属性",required = true) ：打在参数前，对参数做描述
 */
@RestController
@RequestMapping("/dept")
@Api(value = "部门的API",description="部门相关的CRUD功能")
public class DeptmentController {
    //创建业务层对象
    @Resource
    private IDepartmentService departmentService ;
    //增加或者修改
    @PutMapping
    @ApiOperation(value = "新增或修改操作" )
    @PreAuthorize(name = "部门保存",value = "dept:save")
    public AjaxResult  addOrUpdate(@RequestBody Department department ){
        try{
            if (department.getId()==null){
                departmentService.add(department);
                //给字段dirpath设置值，等价于在添加的功能上增强（增加后就有id，所以放在这里增强）
                if(department.getParent().getId()==null){
                    //此处选择获取聚合属性的id，因为前端都是传的聚合属性对象，如果该对象的id值为空就没有选，此时就把自己当做顶级元素+/
                    department.setDirPath("/"+department.getId());//此处department.getId()是因为sql里面开启了主键回填
                }else{//不为空就根据传入的id,去查找父级对象的dirpath
                    Department father =  departmentService.selectOne(department.getParent().getId());
                    //拼接父级dirpath和自增长的id
                    department.setDirPath(father.getDirPath()+"/"+department.getId());
                }
                //设置后刷新页面（使用修改去刷新页面）
                departmentService.update(department);
                return AjaxResult.me().setSuccess(true).setMessage("添加成功");
            }else{
                departmentService.update(department);
                return AjaxResult.me().setSuccess(true).setMessage("修改成功");
            }
        }catch (Exception e ){
            return AjaxResult .me() .setSuccess(false ).setMessage("操作失败");
        }
    }
    //删除
    @PreAuthorize(name = "部门删除",value = "dept:delete")
    @DeleteMapping("/{id}")
    @ApiOperation(value = "通过ID删除" )
    public AjaxResult  delete(@PathVariable("id") Long id){
        try{
            departmentService.delete(id);
            return AjaxResult.me().setSuccess(true).setMessage("删除成功");
        }catch (Exception e ){
        return AjaxResult .me() .setSuccess(false ).setMessage("删除失败");
        }

    }
    //查询一条数据
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询" )
    public Department selectOne(@PathVariable("id") Long id){
        return departmentService.selectOne(id);
    }
    //查询多条数据
    @GetMapping
    @ApiOperation(value = "查询所有数据" )
    public List<Department> selectAll(){
        return departmentService.selectAll();
    }
    //分页
    @PostMapping
    @ApiOperation(value = "分页查询" )
    @PreAuthorize(name = "部门列表",value = "dept:list")
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query){
       return  departmentService.pageQuery(query);
    }
    //批量删除
    @PatchMapping
    @ApiOperation(value = "批量删除" )
    public AjaxResult batchDelete(@RequestBody List<Long> ids){
        try{
            departmentService.batchDelete(ids);
            return AjaxResult.me().setSuccess(true).setMessage("批量删除成功");
        }catch (Exception e ){
            return AjaxResult .me() .setSuccess(false ).setMessage("网络繁忙");
        }

    }
    @GetMapping("/tree")
    @ApiOperation(value = "无限极树" )
    public List<Department> queryTree(){
        return departmentService.buildTree();

    }
}
